package com.longge.websocket.timer;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import lombok.extern.slf4j.Slf4j;

@EnableScheduling
@Component
@Slf4j
public class SseTimer {
	private Set<SseEmitter> clients = new CopyOnWriteArraySet<>();
	
	public void addClient(SseEmitter sseEmitter) {
		clients.add(sseEmitter);
	}
	
	@Scheduled(cron = "0/5 * * * * ?")
	public void send() {
		clients.iterator().forEachRemaining(item -> {
			try {
				String msg = String.valueOf(RandomUtils.nextInt(0, Integer.MAX_VALUE));
				item.send(msg);
				log.info("send message:{}", msg);
			} catch (Exception e) {
				log.error("send error", e);
				if(e instanceof IllegalStateException) {
					clients.remove(item);
					item.completeWithError(e);
				}
			}
		});
	}
}
